<script setup>
import {getCurrentInstance, nextTick, onMounted, ref} from "vue";
import eventBus  from '../../event/eventBus.js';
import DialogView from "../DialogView.vue";
import MarkIcon from '../../assets/image/watericon6.png'
import $ from 'jquery';
import { ElMessage } from "element-plus";
const NAME = '定位';
const DOWN = '导出';

let isMark = ref(false);
const name = ref('')
const detailDialog = ref(false)
const { appContext } = getCurrentInstance();
let global = appContext.config.globalProperties;
let currOverlayArr = [];
let markers = [];
let currentIndex = null;
let _drawIndex = 0;

let tooltip = document.createElement('DIV');
document.body.appendChild(tooltip);
tooltip.style =
    'position: absolute;background: rgba(0,0,0,0.5); z-index: 999;line-height: 18px;pointer-events: none;';
tooltip.innerHTML =
    '<span style="color: #fff; font-size: 12px;padding:4px">点击创建标记点</span>'
tooltip.style.display = 'block'

onMounted(() => {
  eventBus.on('mapToolBarClick', (data) => {
    if(data == NAME){
      isMark.value = true;
      showTooltip() // 显示tooltip提示
      addPoint()
    }else if(data == DOWN){
      // 导出
      removeHandlers()
      hideTooltip()
      let hasMark = false;
      markers.forEach(mark => {
        if (mark) {
          hasMark = true
        }
      })
      if (hasMark) {
        // 导出标记点
        positionToGeoJson()
      } else {
        ElMessage({
            message: '暂无标记',
            type: 'warning'
        })
      }
    }else{
      removeOverlay()
      isMark.value = false;
    }
  });
});
const addPoint = () => {
  getPoint((lng, lat) => {
    markerOverlay(pickPosition(lng, lat))
    markers.push({
      lng, lat, name: ''
    })
    currentIndex = _drawIndex
    nextTick(() => {
      detailDialog.value = true
    })
    _drawIndex++
  })
}
// 测量结果的浮窗
function markerOverlay(position) {
    if (global.$viewer) {
        let divStr = `<div class="marker" index="${_drawIndex}" style="position: absolute;width: 14px;
          height: 20px;
          cursor: pointer;
          background-repeat: no-repeat;
          background-size: 20px 20px;
          background-position: -4px;
          background-image: url(${MarkIcon});"></div>`;
        let element = $(divStr)[0];
        let currOverlay;
        let option = {
            element: element,
            position: position,
            offset: { //默认整个div的左上角，跟地图上指定的点重合
                x: -6, //向屏幕左边平移的像素值
                y: -20 //向屏幕下方平移的像素值
            }
        };
        currOverlay = new Cesium.Overlay(option);
        currOverlayArr.push(currOverlay)
        global.$viewer.addOverlay(currOverlay);
        $('.marker').click(function() {
            let index = $(this).attr('index')
            currentIndex = +index
            name.value = markers[currentIndex].name;
            detailDialog.value = true;
        })
    }
}
let handler = null;
const getPoint = (call) => {
  // 地形拾取：
  handler = new Cesium.ScreenSpaceEventHandler(global.$viewer.canvas);
  handler.setInputAction((event) => {
      let ray = global.$viewer.camera.getPickRay(event.position);
      let c3 = global.$viewer.scene.globe.pick(ray,global.$viewer.scene);
      let cartographic= Cesium.Cartographic.fromCartesian(c3);
      let lat = Cesium.Math.toDegrees(cartographic.latitude);
      let lng = Cesium.Math.toDegrees(cartographic.longitude);
      // console.log(lng.toFixed(6)+', '+ lat.toFixed(6))
      call(lng.toFixed(6), lat.toFixed(6))
      removeHandlers()
      hideTooltip()
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  handler.setInputAction(function (movement) {
      setTooltipPos(movement) // 设置tooltip位置
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
function removeHandlers() {
    handler && handler.destroy();
    handler = null;
}
// 获取坐标
function pickPosition(lng, lat) {
    return Cesium.Cartesian3.fromDegrees(lng, lat, 0)
}
function setTooltipPos(movement) {
    tooltip.style.left = movement.endPosition.x + 10 + 'px'
    tooltip.style.top = movement.endPosition.y - 27 + 'px'
}
function showTooltip() {
    tooltip.style.display = 'block'
}
function hideTooltip() {
    tooltip.style.display = 'none'
}
// 清除
function removeOverlay() {
    removeHandlers()
    hideTooltip()
    if (currOverlayArr.length) {
        currOverlayArr.forEach(item => {
            item&&item.destroy();
        })
        currOverlayArr = [];
    }
    markers = [];
    _drawIndex = 0;
    currentIndex = null;
}
const closeDialog = (v) => {
  name.value = ''
  detailDialog.value = false
}
const save = () => {
  if (name.value) {
    markers[currentIndex].name = name.value
    closeDialog()
  } else {
    ElMessage({
        message: '请输入标记名称',
        type: 'warning'
    })
  }
}
const removeMark = () => {
  currOverlayArr[currentIndex].destroy();
  currOverlayArr[currentIndex] = null;
  markers[currentIndex] = null;
  currentIndex = null;
  closeDialog()
}
function positionToGeoJson() {

  let geojsonPoint = {
    "type": "FeatureCollection",
    "features": []
  }
  markers.forEach(pt => {
    if (pt) {
      geojsonPoint['features'].push({
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [Number(pt.lng), Number(pt.lat)]
        },
        "properties": {
          "name": pt.name,
          "description": ""
        }
      })
    }
  })
  // console.log(geojsonPoint)

  let geojson = JSON.stringify(geojsonPoint) 
  //encodeURIComponent解决中文乱码
  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(geojson);
  //通过创建a标签实现
  let link = document.createElement("a");
  link.href = uri;
  //对下载的文件命名
  link.download =  "定位点坐标.geojson";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
</script>

<template >
  <div v-if="isMark">
    <DialogView :visible="detailDialog" width="200" title="添加标记" :footer="false" @update:visible="(v) => (closeDialog(v))">
        <div class="mark">
          <div class="content"><el-input v-model="name" /></div>
          <div class="btns">
            <el-button type="primary" size="small" @click="save">确定</el-button>
            <el-button type="primary" size="small" @click="removeMark">删除</el-button>
          </div>
        </div>
    </DialogView>
  </div>
</template>
<style lang="less" scoped>
.mark {
  .content {
    padding: 6px 14px;
  }
  .btns {
    margin-top: 20px;
    text-align: center;
  }
}
</style>